﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeiXin.Base.Pay.Lib;

namespace WeiXin.Base.Pay
{
    /// <summary>
    /// 红包
    /// <remarks>http://www.cnblogs.com/txw1958/p/weixin-send-group-redpack.html</remarks>
    /// </summary>
    public class RedPack
    {
        /// <summary>
        /// 发送普通红包
        /// 普通红包：一次只发放给一个用户。
        /// <remarks>
        /// 详细说明：https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
        /// </remarks>
        /// </summary>
        /// <param name="mch_billno">商户订单号（每个订单号必须唯一）组成：mch_id+yyyymmdd+10位一天内不能重复的数字。接口根据商户订单号支持重入，如出现超时可再调用。</param>
        /// <param name="send_name">红包发送者名称</param>
        /// <param name="re_openid">接受红包的用户，用户在wxappid下的openid</param>
        /// <param name="total_amount">付款金额，单位分</param>
        /// <param name="total_num">红包发放总人数</param>
        /// <param name="wishing">红包祝福语</param>
        /// <param name="act_name">活动名称</param>
        /// <param name="remark">备注信息</param>
        /// <param name="sReturnMsg">返回的信息</param>
        /// <param name="scene_id">场景id</param>
        /// <param name="risk_info">活动信息</param>
        /// <param name="consume_mch_id">资金授权商户号 服务商替特约商户发放时使用</param>
        /// <returns></returns>
        public static bool SendRedPack(string mch_billno, string wxappid, string send_name, string re_openid, string total_amount,
            string total_num, string wishing, string act_name, string remark, out string sReturnMsg, string scene_id = "",
            string risk_info = "", string consume_mch_id = "")
        {
            #region 发送普通红包
            bool bResult = false;
            sReturnMsg = string.Empty;
            WxPayData data = new WxPayData();
            data.SetValue("mch_billno", mch_billno);
            data.SetValue("send_name", send_name);
            data.SetValue("re_openid", re_openid);
            data.SetValue("total_amount", int.Parse(total_amount));
            data.SetValue("total_num", int.Parse(total_num));
            data.SetValue("wishing", wishing);
            data.SetValue("act_name", act_name);
            data.SetValue("remark", remark);

            if (!string.IsNullOrEmpty(scene_id))
                data.SetValue("scene_id", scene_id);
            if (!string.IsNullOrEmpty(risk_info))
                data.SetValue("risk_info", risk_info);
            if (!string.IsNullOrEmpty(consume_mch_id))
                data.SetValue("consume_mch_id", consume_mch_id);

            WxPayData result = WxPayApi.RedPack(data);
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString().Equals("SUCCESS"))
            {
                if (result.IsSet("result_code") && result.GetValue("result_code").ToString() == "SUCCESS")
                {

                    sReturnMsg = "{\"err_code_des\":\"" + result.GetValue("err_code_des").ToString() +
                                 "\",\"send_listid\":\"" + result.GetValue("send_listid").ToString() + "\"}";
                    bResult = true;
                }
            }
            else {
                sReturnMsg = result.GetValue("return_msg").ToString();
            }
            return bResult;
            #endregion
        }


        /// <summary>
        /// 发放裂变红包
        /// <remarks>
        /// 裂变红包：一次可以发放一组红包。首先领取的用户为种子用户，种子用户领取一组红包当中的一个，并可以通过社交分享将剩下的红包给其他用户。裂变红包充分利用了人际传播的优势。
        /// 详细说明：https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5&index=4  
        /// http://www.cnblogs.com/txw1958/p/weixin-send-group-redpack.html
        /// </remarks>
        /// </summary>
        /// <param name="mch_billno">商户订单号（每个订单号必须唯一）组成：mch_id+yyyymmdd+10位一天内不能重复的数字。接口根据商户订单号支持重入，如出现超时可再调用。</param>
        /// <param name="send_name">红包发送者名称</param>
        /// <param name="re_openid">接受红包的用户，用户在wxappid下的openid</param>
        /// <param name="total_amount">付款金额，单位分</param>
        /// <param name="total_num">红包发放总人数</param>
        /// <param name="amtType">红包金额设置方式</param>
        /// <param name="amt_list">各红包具体金额，自定义金额时必须设置，单位分(格式：200|100|100)</param>
        /// <param name="wishing">红包祝福语</param>
        /// <param name="act_name">活动名称</param>
        /// <param name="remark">备注信息</param>
        /// <param name="sReturnMsg">返回的信息</param>
        /// <param name="scene_id">场景id</param>
        /// <param name="risk_info">活动信息</param>
        /// <param name="consume_mch_id">资金授权商户号 服务商替特约商户发放时使用</param>
        /// <returns></returns>
        public static bool SendGroupRedPack(string mch_billno, string wxappid, string send_name, string re_openid, string total_amount,
            string total_num, RedPackAmt_Type amtType, string amt_list, string wishing, string act_name, string remark,
            out string sReturnMsg, string scene_id = "", string risk_info = "", string consume_mch_id = "")
        {
            #region 发放裂变红包
            bool bResult = false;
            sReturnMsg = string.Empty;
            WxPayData data = new WxPayData();
            data.SetValue("mch_billno", mch_billno);
            data.SetValue("send_name", send_name);
            data.SetValue("re_openid", re_openid);
            data.SetValue("total_amount", int.Parse(total_amount));
            data.SetValue("total_num", int.Parse(total_num));

            /* amt_type
            红包金额设置方式
            ALL_RAND—全部随机,商户指定总金额和红包发放总人数，由微信支付随机计算出各红包金额
            ALL_SPECIFIED—全部自定义
            SEED_SPECIFIED—种子红包自定义，其他随机
            */
            data.SetValue("amt_type", amtType);
            if (amtType == RedPackAmt_Type.ALL_SPECIFIED)
                data.SetValue("amt_list", amt_list);//各红包具体金额，自定义金额时必须设置，单位分

            data.SetValue("wishing", wishing);
            data.SetValue("act_name", act_name);
            data.SetValue("remark", remark);

            if (!string.IsNullOrEmpty(scene_id))
                data.SetValue("scene_id", scene_id);
            if (!string.IsNullOrEmpty(risk_info))
                data.SetValue("risk_info", risk_info);
            if (!string.IsNullOrEmpty(consume_mch_id))
                data.SetValue("consume_mch_id", consume_mch_id);

            WxPayData result = WxPayApi.RedPack(data, true);
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString().Equals("SUCCESS"))
            {
                if (result.IsSet("result_code") && result.GetValue("result_code").ToString() == "SUCCESS")
                {

                    sReturnMsg = "{\"err_code_des\":\"" + result.GetValue("err_code_des").ToString() +
                                 "\",\"send_listid\":\"" + result.GetValue("send_listid").ToString() + "\"}";
                    bResult = true;
                }
            }
            else {
                sReturnMsg = result.GetValue("return_msg").ToString();
            }
            return bResult;
            #endregion
        }

        /// <summary>
        /// 查询红包记录 用于商户对已发放的红包进行查询红包的具体信息，可支持普通红包和裂变包。
        /// </summary>
        /// <param name="mch_billno">商户发放红包的商户订单号</param>
        /// <param name="bill_type">订单类型</param>
        /// <param name="sReturnMsg">返回的信息</param>
        /// <returns></returns>
        public static bool Query(string mch_billno, string bill_type, out string sReturnMsg)
        {
            #region 查询红包记录
            bool bResult = false;
            sReturnMsg = string.Empty;
            WxPayData data = new WxPayData();
            data.SetValue("mch_billno", mch_billno);
            data.SetValue("bill_type", bill_type);
            WxPayData result = WxPayApi.RedPackQuery(data);
            sReturnMsg = result.ToXml();
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString().Equals("SUCCESS"))
            {
                if (result.IsSet("result_code") && result.GetValue("result_code").ToString() == "SUCCESS")
                    bResult = true;
            }
            return bResult;
            #endregion
        }
    }

}
